<template>
  <div class="app-container table-none">
    <div class="flex">
      <div class="container-header">
        日期： <el-date-picker size="small" v-model="selectDate" type="date" @change="bindSelectDate" placeholder="请选择" />
      </div>
      <div>

        <el-button type="info" plain icon="Tickets" @click="handleDay">收费站日报表</el-button>
        <el-button type="warning" plain icon="Download" v-hasPermi="['information:center']" @click="handleExport">导出</el-button>
        <el-button @click="bindHistoryShow">历史数据补充</el-button>
      </div>

    </div>

    <el-collapse v-model="activeName" accordion @change="bindChangeAccordion" v-if="postData&&postData.length">
      <el-collapse-item :name="i+1" v-for="(opt,i) in activeList" :key="i" v-hasPermi="i==7||i==8?['system:ticket:card']:['system:ticket:data']">
        <template #title>
          <span class="accordion-title"> {{opt.title}}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span
            :class="statusArr.includes(opt.title)&&opt.status==1?'text-green':statusArr.includes(opt.title)&&opt.status==2?'text-red':'text-orange'"
            v-if="i!=8">{{statusArr.includes(opt.title)&&opt.status==1?'已上报':statusArr.includes(opt.title)&&opt.status==2?'延迟上报':'待上报'}}</span>
        </template>
        <el-table :data="tableData" :span-method="arraySpanMethod" :cell-class-name="tableRowClassName" border :show-header="false"
          v-if="activeName!=8&&activeName!=9&&activeName!=10">
          <el-table-column prop="test1" label="通行量(辆)" width="108" />
          <el-table-column prop="test2" label="" width="123">
            <!-- <template #default="scope">
              <div v-if="scope.row.isInput&&scope.row.remark=='remark'">
                <el-input v-model="remark" placeholder="请输入" @input="bindChangeRemark($event,'remark')" class="inputDeep" />
              </div>
            </template> -->
          </el-table-column>
          <el-table-column :prop="'amount'+(index+1)" v-for="(item,index) in activeNum" :key="index" :ref="i+'type1'+index">
            <template #default="scope">
              <!-- 正式版  <el-input-number v-numberOnly    试用版删除 :disabled="statusArr.includes(opt.title)&&opt.allowMdf!=1"-->
              <div v-if="scope.row.isInput&&postData[index]&&postData[index].header">
                <el-input v-numberOnly :controls="false" ref="autoFocus"
                  :disabled="statusArr.includes(opt.title)&&(opt.allowMdf!=1&&!isWithinHours(queryParams.reportDate))"
                  v-model="postData[index][scope.row.index==0?'exTraffic':scope.row.index==1? 'enTraffic':'fee']" placeholder="请输入"
                  @keyup="nextFocu($event,index, scope.row.index,1)"
                  @input="bindChangeForm($event,index,scope.row.index==0?'exTraffic':scope.row.index==1? 'enTraffic':'fee',1)"
                  @change="clearPlusMinus($event,index,scope.row.index==0?'exTraffic':scope.row.index==1? 'enTraffic':'fee')" class="inputDeep" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="合计" class-name="bg-orange" width="108" />
        </el-table>
        <el-table :data="tableData2" :span-method="arrayBottomSpanMethod" :cell-class-name="tableRowBottomClassName" border :show-header="false"
          v-if="activeName!=8&&activeName!=9&&activeName!=10">
          <el-table-column prop="test1" label="通行量(辆)" width="108" />
          <el-table-column prop="test2" label="" width="123"></el-table-column>
          <el-table-column :prop="'amount'+(index+1)" v-for="(item,index) in activeName==2||activeName==4||activeName==6||activeName==7?6:4" :key="index">
            <template #default="scope">
              <div v-if="scope.row.isInput">
                <!-- 正式版  <el-input-number v-numberOnly   试用版删除  :disabled="statusArr.includes(opt.title)&&opt.allowMdf!=1"-->
                <el-input v-numberOnly :precision="2" ref="autoFocus" :controls="false"
                  :disabled="statusArr.includes(opt.title)&&opt.allowMdf!=1&&!isWithinHours(queryParams.reportDate)"
                  v-model="postData[index][scope.row.index==0?'exTraffic':scope.row.index==1? 'enTraffic':'fee']"
                  @keyup="nextFocu($event,index, scope.row.index,2)" placeholder="请输入"
                  @input="bindChangeForm($event,index,scope.row.index==0?'exTraffic':scope.row.index==1? 'enTraffic':'fee',2)"
                  @change="bindFixed($event,index,scope.row.index==0?'exTraffic':scope.row.index==1? 'enTraffic':'fee')" class="inputDeep" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="合计" class-name="bg-orange" width="108" />
        </el-table>

        <el-table :data="tableData3" style="width: 100%" v-if="activeName==8">
          <el-table-column prop="type" label="" width="180" v-if="activeName==8"></el-table-column>
          <el-table-column prop="previousBalance" label="前存" width="180">
            <template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.previousBalance" placeholder="请输入" @input="bindChangeRoutine($event,'previousBalance',0)"
                  @keyup="nextFocu($event,0, scope.$index,3)" class="inputDeep" />
              </div>
            </template></el-table-column>
          <el-table-column prop="newCollar" label="新领" width="180"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.newCollar" placeholder="请输入" @input="bindChangeRoutine($event,'newCollar',0)" class="inputDeep"
                  @keyup="nextFocu($event,1, scope.$index,3)" />
              </div>
            </template></el-table-column>

          <el-table-column prop="allotOut" label="调拨"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.allotOut" placeholder="请输入" @input="bindChangeRoutine($event,'allotOut',0)" class="inputDeep"
                  @keyup="nextFocu($event,3,scope.$index,3)" />
              </div>
            </template></el-table-column>
          <el-table-column prop="sendOut" label="发出" v-if="activeName==8"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.sendOut" placeholder="请输入" @input="bindChangeRoutine($event,'sendOut',0)" class="inputDeep"
                  @keyup="nextFocu($event,4, scope.$index,3)" />
              </div>
            </template></el-table-column>
          <el-table-column prop="recycle" label="回收" v-if="activeName==8"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.recycle" placeholder="请输入" @input="bindChangeRoutine($event,'recycle',0)" class="inputDeep"
                  @keyup="nextFocu($event,5, scope.$index,3)" />
              </div>
            </template></el-table-column>
          <el-table-column prop="dayInventory" label="结存"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.dayInventory" placeholder="请输入" @input="bindChangeRoutine($event,'dayInventory',0)" class="inputDeep"
                  :disabled="true" @keyup="nextFocu($event,6, scope.$index,3)" />
              </div>
            </template></el-table-column>
        </el-table>
        <el-table :data="tableData5" style="width: 100%" v-if="activeName==8">
          <el-table-column prop="type" label="" width="180" v-if="activeName==8"></el-table-column>
          <el-table-column prop="previousBalance" label="前存" width="180">
            <template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.previousBalance" placeholder="请输入" @input="bindChangeRoutine($event,'previousBalance',1)"
                  @keyup="nextFocu($event,0, scope.$index,3)" class="inputDeep" />
              </div>
            </template></el-table-column>
          <el-table-column prop="newCollar" label="新领" width="180"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.newCollar" placeholder="请输入" @input="bindChangeRoutine($event,'newCollar',1)" class="inputDeep"
                  @keyup="nextFocu($event,1, scope.$index,3)" />
              </div>
            </template></el-table-column>

          <el-table-column prop="sendOut" label="使用" v-if="activeName==8"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.sendOut" placeholder="请输入" @input="bindChangeRoutine($event,'sendOut',1)" class="inputDeep"
                  @keyup="nextFocu($event,4, scope.$index,3)" />
              </div>
            </template></el-table-column>
          <el-table-column prop="recycle" label="其中作废" v-if="activeName==8"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.recycle" placeholder="请输入" @input="bindChangeRoutine($event,'recycle',1)" class="inputDeep"
                  @keyup="nextFocu($event,5, scope.$index,3)" />
              </div>
            </template></el-table-column>
          <el-table-column prop="dayInventory" label="结存"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.dayInventory" placeholder="请输入" @input="bindChangeRoutine($event,'dayInventory',1)" class="inputDeep"
                  :disabled="true" @keyup="nextFocu($event,6, scope.$index,3)" />
              </div>
            </template></el-table-column>
        </el-table>
        <el-table :data="tableData6" style="width: 100%" v-if="activeName==8">
          <el-table-column prop="type" label="" width="180" v-if="activeName==8"></el-table-column>
          <el-table-column prop="previousBalance" label="前存" width="180">
            <template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.previousBalance" placeholder="请输入" @input="bindChangeRoutine($event,'previousBalance',2)"
                  @keyup="nextFocu($event,0, scope.$index,3)" class="inputDeep" />
              </div>
            </template></el-table-column>
          <el-table-column prop="newCollar" label="新领" width="180"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.newCollar" placeholder="请输入" @input="bindChangeRoutine($event,'newCollar',2)" class="inputDeep"
                  @keyup="nextFocu($event,1, scope.$index,3)" />
              </div>
            </template></el-table-column>

          <el-table-column prop="sendOut" label="使用" v-if="activeName==8"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.sendOut" placeholder="请输入" @input="bindChangeRoutine($event,'sendOut',2)" class="inputDeep"
                  @keyup="nextFocu($event,4, scope.$index,3)" />
              </div>
            </template></el-table-column>
          <el-table-column prop="recycle" label="其中作废" v-if="activeName==8"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.recycle" placeholder="请输入" @input="bindChangeRoutine($event,'recycle',2)" class="inputDeep"
                  @keyup="nextFocu($event,5, scope.$index,3)" />
              </div>
            </template></el-table-column>
          <el-table-column prop="dayInventory" label="结存"><template #default="scope">
              <div>
                <el-input v-numberOnly v-model="scope.row.dayInventory" placeholder="请输入" @input="bindChangeRoutine($event,'dayInventory',2)" class="inputDeep"
                  :disabled="true" @keyup="nextFocu($event,6, scope.$index,3)" />
              </div>
            </template></el-table-column>
        </el-table>

        <el-descriptions title="" v-if="activeName==9" border class="inputDeep">
          <el-descriptions-item label="备注">
            <el-input type="textarea" v-model="remark" placeholder="请输入" @input="bindChangeRemark" />
          </el-descriptions-item>
        </el-descriptions>

        <!-- 不可删除，正式版需要使用 -->
        <div class="submit">
          <el-button type="primary" @click="bindSubmit" v-hasPermi="i==7||i==8?['system:ticket:reportCard']:['system:ticket:report']"
            v-if="!statusArr.includes(opt.title)||opt.allowMdf==1||isWithinHours(queryParams.reportDate)">提交</el-button>
          <el-popconfirm title="确认发出申请?" @confirm="getformTransferModel(opt.title,opt.id)" width="200px">
            <template #reference>
              <!-- opt.allowMdf!=1|| -->
              <el-button type="primary" v-if="statusArr.includes(opt.title)&&(!isWithinHours(queryParams.reportDate))"
                v-hasPermi="i==7||i==8?['system:ticket:reportCard']:['system:ticket:report']">申请修改</el-button>
            </template>
          </el-popconfirm>
        </div>

        <!-- 试用期 -->
        <!-- <div class="submit">
          <el-button type="primary" @click="bindSubmit" v-hasPermi="i==7||i==8?['system:ticket:reportCard']:['system:ticket:report']">提交</el-button>
        </div> -->

      </el-collapse-item>

    </el-collapse>

    <el-dialog title="补充历史数据" v-model="open" width="800px" append-to-body>
      <!--  replenish_type -->
      <el-table :data="historyData" style="width: 100%" height="650">
        <el-table-column prop="name" label="名称" width="180" align="center"></el-table-column>
        <el-table-column prop="yearCumulative" label="本年累计" width="180" align="center">
          <template #default="scope">
            <div>
              <el-input v-model="scope.row.yearCumulative" placeholder="请输入" @input="bindChangeHistory($event,'yearCumulative',scope.$index)"
                class="inputDeep" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="cumulative" label="通车后累计" width="180" align="center">
          <template #default="scope">
            <div>
              <el-input v-model="scope.row.cumulative" placeholder="请输入" @input="bindChangeHistory($event,'cumulative',scope.$index)" class="inputDeep" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="monthCumulative" label="本月累计" width="180" align="center">
          <template #default="scope">
            <div>
              <el-input v-model="scope.row.monthCumulative" placeholder="请输入" @input="bindChangeHistory($event,'monthCumulative',scope.$index)"
                class="inputDeep" />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
  
<script setup name="User">
import moment from 'moment'
import { listTicket, addTicke, InfoTicket, queryCardTicke, addCardTicke, postSupplement, getSupplementList } from "@/api/charge/ticket";
import { postDefinitionStart } from "@/api/charge/charge";
import { definitionStart } from "@/api/flowable/definition";

import useUserStore from '@/store/modules/user'

const router = useRouter();
const { proxy } = getCurrentInstance();
const { report_type, replenish_type } = proxy.useDict('report_type', 'replenish_type');
let postDataDefult = [{ enTraffic: '', exTraffic: '', fee: "", header: 'A' }, { enTraffic: '', exTraffic: '', fee: "", header: 'B' }, { enTraffic: '', exTraffic: '', fee: "", header: 'C' },
{ enTraffic: '', exTraffic: '', fee: "", header: 'D' }, { enTraffic: '', exTraffic: '', fee: "", header: 'E' }, { enTraffic: '', exTraffic: '', fee: "", header: 'H' }]
const userStore = useUserStore()
const activeName = ref('1')
// { title: '电子发票使用情况日报表' },
const activeList = ref([{ title: '收费站现金客车日报表' }, { title: '收费站现金货车日报表' }, { title: '收费站ETC客车日报表' }, { title: '收费站ETC货车日报表' }, { title: '收费站非现金客车日报表' }, { title: '收费站非现金货车日报表' }, { title: '运输鲜活农产品车辆日报表' }, { title: '卡券使用情况报表' }, { title: '特殊情况备注' }])
const localhostData = ref([{ title: '收费站现金客车日报表' }, { title: '收费站现金货车日报表' }, { title: '收费站ETC客车日报表' }, { title: '收费站ETC货车日报表' }, { title: '收费站非现金客车日报表' }, { title: '收费站非现金货车日报表' }, { title: '运输鲜活农产品车辆日报表' }, { title: '卡券使用情况报表' }, { title: '特殊情况备注' }])
const postData = ref(postDataDefult)
const selectDate = ref()//日期
const ticketName = ref("收费站现金客车日报表")
const info = ref({})
const statusArr = ref([])
const deptName = ref()
const remark = ref()
const activeNum = ref(5)
const rowDetails = ref({})
const queryParams = ref({ reportDate: '', deptId: '' })
const tableData = ref([{ test1: "通行量(辆)", test2: "", amount1: 'A', amount2: "B", amount3: "C", amount4: "D", amount5: "H" }, { test1: "出口", isInput: true, index: 0 }, { test1: "入口", isInput: true, index: 1 }])
const tableData2 = ref([{ test1: "通行费(元)", test2: '', amount1: 'A', amount2: "B", amount3: "C", amount4: "D" }, { test1: "", test2: '', index: 2, isInput: true }])
const tableData3 = ref([{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: 'CPC卡' }])
const tableData4 = ref([{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '' }])
const tableData5 = ref([{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: '微机票' }])
const tableData6 = ref([{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: '节假日纸券' }])

const open = ref(false)
const historyData = ref([])
const deptId = ref()
const saveArr = ref([])
const selectAccordion = ref()
const tableNum = ref([0, 14, 34, 48, 68, 76, 88, 100]) //[14,20,14,20,8,12,12,21]
const postDataNumber = ref([])
// 表格
const arraySpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (columnIndex === 0) {
    if (rowIndex === 0) {
      return {
        rowspan: 3,
        colspan: 1,
      }
    }
  } else if (rowIndex === 1 && columnIndex == 1) {
    return {
      rowspan: 0,
      colspan: 0
    }
  } else if (rowIndex === 2 && columnIndex == 1) {
    return {
      rowspan: 0,
      colspan: 0
    }
  }

}

const arrayBottomSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (columnIndex === 0) {
    if (rowIndex === 0) {
      return {
        rowspan: 2,
        colspan: 2,
      }
    } else if (rowIndex == 2) {
      return {
        rowspan: 1,
        colspan: 2,
      }
    } else if (rowIndex == 1) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  } else if (rowIndex === 0 && columnIndex == 1) {
    return {
      rowspan: 0,
      colspan: 0
    }
  } else if (rowIndex == 1 && columnIndex == 1) {
    return {
      rowspan: 0,
      colspan: 0
    }
  } else if (rowIndex === 2 && columnIndex == 1) {
    return {
      rowspan: 1,
      colspan: 6,
    }
  } else if (rowIndex === 2 && columnIndex != 1 && columnIndex != 0) {
    return {
      rowspan: 0,
      colspan: 0
    }
  }

}
// 样式
const tableRowClassName = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (rowIndex === 0) {
    return 'warning-row'
  } else if (rowIndex === 3) {
    return 'success-row'
  } else if (rowIndex === 5 && (columnIndex == 0)) {
    return 'info-row'
  } else if (rowIndex === 1 && columnIndex == 0) {
    return 'warning-row'
  } else if (rowIndex === 2 && columnIndex == 0) {
    return 'warning-row'
  }
  return ''
}
const tableRowBottomClassName = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (rowIndex === 0) {
    return 'success-row'
  } else if (rowIndex === 2 && (columnIndex == 0)) {
    return 'info-row'
  }
  return ''
}



watch(() => report_type.value, newVal => {
  if (newVal) {
    newVal.forEach(item => {
      historyData.value.push({ name: item.label, reportType: item.value, deptId: deptId.value })
    })
  }
},
  { immediate: true }
)

/** 查询列表 */
function getList(date) {
  if (date) {
    queryParams.value.reportDate = date
  }
  listTicket(queryParams.value).then(res => {
    info.value = res.data;
    statusArr.value = []
    if (res.code == 200 && res.data && res.data.length > 0) {
      res.data.forEach(item => {
        statusArr.value.push(item.ticketName)
        activeList.value.forEach(element => {
          if (element.title == item.ticketName) {
            element.status = item.status;
            element.allowMdf = item.allowMdf;
            element.id = item.id;

          }
        })
      })
    }

  });
};

function deepClone(obj) {
  let objClone = Array.isArray(obj) ? [] : {}
  if (obj && typeof obj === 'object') {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        // 判断ojb子元素是否为对象，如果是，递归复制
        if (obj[key] && typeof obj[key] === 'object') {
          objClone[key] = deepClone(obj[key])
        } else {
          // 如果不是，简单复制
          objClone[key] = obj[key]
        }
      }
    }
  }
  return objClone
}


const setLocationData = (data, historyData, ticketName) => {
  
  if (historyData) {
    localhostData.value.forEach((item, index) => {
      if (item.title == ticketName) {

        let arr = []
        historyData.forEach((opt, i) => {
          arr.push(opt)
          // historyData.forEach(res => {
          //   if (opt.header == res.header) {
          //     arr[i] = res
          //   }
          // })


        })
    
        localhostData.value[index] = { ...arr, ticketName: ticketName, title: ticketName }

      
      }
    })

   
  }
}
const bindChangeAccordion = (val) => {
  let historyData = deepClone(postData.value)
  let oldTitle = JSON.parse(JSON.stringify(ticketName.value))




  if (!val) {
    return;
  }
  selectAccordion.value = val;

  ticketName.value = activeList.value[Number(val) - 1].title;
  if (val == 2 || val == 4) {
    activeNum.value = 7
    let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'H']
    tableData.value = [{ test1: "通行量(辆)", test2: "", amount1: 'A', amount2: "B", amount3: "C", amount4: "D", amount5: "E", amount6: "F", amount7: "H" }, { test1: "出口", isInput: true, index: 0 }, { test1: "入口", isInput: true, index: 1 }]
    tableData2.value = [{ test1: "通行费(元)", test2: '', amount1: 'A', amount2: "B", amount3: "C", amount4: "D", amount5: "E", amount6: "F" }, { test1: "", test2: '', index: 2, isInput: true }]
    postData.value = []
    for (let i = 0; i <= 6; i++) {
      postData.value.push({ enTraffic: null, exTraffic: null, fee: null, header: arr[i] })
    }

    setLocationData(postData.value, historyData, oldTitle)
    getInfo()
  } else if (val == 5) {
    activeNum.value = 4
    let arr = ['A', 'B', 'C', 'D',]
    tableData.value = [{ test1: "通行量(辆)", test2: "", amount1: 'A', amount2: "B", amount3: "C", amount4: "D" }, { test1: "出口", isInput: true, index: 0 }]
    tableData2.value = [{ test1: "通行费(元)", test2: '', amount1: 'A', amount2: "B", amount3: "C", amount4: "D" }, { test1: "", test2: '', index: 2, isInput: true }]
    postData.value = []
    for (let i = 0; i <= 3; i++) {
      postData.value.push({ enTraffic: null, exTraffic: null, fee: null, header: arr[i] })
    }
    setLocationData(postData.value, historyData, oldTitle)
    getInfo()
  } else if (val == 6 || val == 7) {
    activeNum.value = 6
    let arr = ['A', 'B', 'C', 'D', 'E', 'F']
    tableData.value = [{ test1: "通行量(辆)", test2: "", amount1: 'A', amount2: "B", amount3: "C", amount4: "D", amount5: "E", amount6: "F" }, { test1: "出口", isInput: true, index: 0 }]
    tableData2.value = [{ test1: "通行费(元)", test2: '', amount1: 'A', amount2: "B", amount3: "C", amount4: "D", amount5: "E", amount6: "F" }, { test1: "", test2: '', index: 2, isInput: true }]
    postData.value = []
    for (let i = 0; i <= 5; i++) {
      postData.value.push({ enTraffic: null, exTraffic: null, fee: null, header: arr[i] })
    }
    setLocationData(postData.value, historyData, oldTitle)
    getInfo()
  } else if (val == 8) {
    getCarInfo()
  } else if (val == 9) {
    getInfo()
  } else {
    activeNum.value = 5
    let arr = ['A', 'B', 'C', 'D', 'H']
    tableData.value = [{ test1: "通行量(辆)", test2: "", amount1: 'A', amount2: "B", amount3: "C", amount4: "D", amount5: "H" }, { test1: "出口", isInput: true, index: 0 }, { test1: "入口", isInput: true, index: 1 }]
    tableData2.value = [{ test1: "通行费(元)", test2: '', amount1: 'A', amount2: "B", amount3: "C", amount4: "D" }, { test1: "", test2: '', index: 2, isInput: true }]
    postData.value = []
    for (let i = 0; i <= 4; i++) {
      postData.value.push({ enTraffic: null, exTraffic: null, fee: null, header: arr[i] })
    }
    
    setLocationData(postData.value, historyData, oldTitle)
  
    getInfo()

  }
  tableData.value[0].total = '合计'
  tableData2.value[0].total = '合计'



}



function getInfo() {
  InfoTicket({ ...queryParams.value, ticketName: ticketName.value }).then(res => {

    info.value = res.data
    postDataNumber.value = []
    if (res.code == 200 && res.data && res.data.list.length > 0) {
      remark.value = res.data.remark;
      let total = 0;
      let total2 = 0;
      let total3 = 0;
      res.data.list.forEach(item => {
        if (item.fee) {
          item.fee = item.fee.toFixed(2)
          total = proxy.cal.accAdd(Number(item.fee), total)
        }
        if (item.enTraffic) {
          total2 = proxy.cal.accAdd(Number(item.enTraffic), total2)
        }
        if (item.exTraffic) {
          total3 = proxy.cal.accAdd(Number(item.exTraffic), total3)
        }
      })
      postData.value = res.data.list;
      tableData2.value[1].total = total;
      if (selectAccordion.value == 5 || selectAccordion.value == 6 || selectAccordion.value == 7) {

        tableData.value[1].total = total3;
      } else {
        tableData.value[2].total = total2;
        tableData.value[1].total = total3;
      }

    } else {
      remark.value = ''


      // 本地存储
      let total = 0;
      let total2 = 0;
      let total3 = 0;
    

      localhostData.value.forEach((opt, index) => {
        if (opt.title == ticketName.value) {      
       
          postData.value.forEach(item => {
            for (let key in opt) {
              if (item.header == opt[key].header) {
                item.enTraffic = opt[key].enTraffic
                item.exTraffic = opt[key].exTraffic
                item.fee= opt[key].fee
              }
            }

            if (item.fee) {
              item.fee = Number(item.fee).toFixed(2)
              total = proxy.cal.accAdd(Number(item.fee), total)
            }
            if (item.enTraffic) {
              total2 = proxy.cal.accAdd(Number(item.enTraffic), total2)
            }
            if (item.exTraffic) {
              total3 = proxy.cal.accAdd(Number(item.exTraffic), total3)
            }

          })
          tableData2.value[1].total = total;
          if (selectAccordion.value == 5 || selectAccordion.value == 6 || selectAccordion.value == 7) {
            tableData.value[1].total = total3;
          } else {
            tableData.value[2].total = total2;
            tableData.value[1].total = total3;
          }


        }
      })
 
    }

  });


};

const getParentElement = (element, tagName, stopAtBody = false) => {
  if (!element || !element.parentElement) return null;
  if (element.parentElement.className.toLowerCase() === tagName.toLowerCase()) {
    return element.parentElement;
  }
  return getParentElement(element.parentElement, tagName, stopAtBody);
}


const nextFocu = (el, index, row, type) => {
  // 右键39  左键37 上38 下40

  // el.stopPropagation()
  // el.preventDefault();
  let td = document.getElementById(el.srcElement.id).parentElement.parentElement.parentElement.parentElement.parentElement
  if (el.keyCode == 39) {
    if (td && td.nextElementSibling) {
      let nextDom = td.nextElementSibling.querySelectorAll('input')[0]
      nextDom ? nextDom.focus() : '';
    }
  } else if (el.keyCode == 37) {
    if (td && td.previousElementSibling) {
      let lastDom = td.previousElementSibling.querySelectorAll('input')[0];
      lastDom ? lastDom.focus() : '';
    }
  } else if (el.keyCode == 38) {
    let upDom = '';
    let lastChilderDom = ''
    if (type == 1 && row == 1) {
      upDom = getParentElement(td, 'el-table__row').previousElementSibling;
      upDom.childNodes[index + 2].querySelectorAll('input')[0].focus();
    } else if (type == 2) {
      upDom = getParentElement(td, 'el-table__inner-wrapper').parentElement.previousElementSibling;
      lastChilderDom = upDom.querySelectorAll('.el-table__row')[upDom.querySelectorAll('.el-table__row').length - 1]
      lastChilderDom.querySelectorAll('input')[index].focus();
    } else if (type == 3) {
      upDom = getParentElement(td, 'el-table__row').previousElementSibling;
      if (upDom && upDom.querySelectorAll('.el-table__cell')) {
        lastChilderDom = upDom.querySelectorAll('.el-table__cell')[index + 1];
        lastChilderDom.querySelectorAll('input')[0].focus();
      }
    }
  } else if (el.keyCode == 40) {
    let downDom = ""
    let lastChilderDom2 = ''
    if (type == 1 && row == 0) {
      downDom = getParentElement(td, 'el-table__row').nextElementSibling;
      downDom.childNodes[index + 2].querySelectorAll('input')[0].focus();
    } else if (type == 1 && row == 1) {
      downDom = getParentElement(td, 'el-table__inner-wrapper').parentElement.nextElementSibling;
      lastChilderDom2 = downDom.querySelectorAll('.el-table__row')[downDom.querySelectorAll('.el-table__row').length - 1];
      let getDom = lastChilderDom2.querySelectorAll('input')[index];
      getDom ? getDom.focus() : "";
    } else if (type == 3) {
      downDom = getParentElement(td, 'el-table__row').nextElementSibling;
      if (downDom && downDom.querySelectorAll('.el-table__cell')) {
        lastChilderDom2 = downDom.querySelectorAll('.el-table__cell')[index + 1];
        lastChilderDom2.querySelectorAll('input')[0].focus();
      }
    }
  }
}

function getCarInfo() {
  queryCardTicke({ ...queryParams.value, ticketName: ticketName.value }).then(res => {

    if (res.code == 200 && res.data) {
      if (activeName.value == 8 && res.data.cardList.length == 3) {
        tableData3.value = [res.data.cardList[0]]

        tableData5.value = [res.data.cardList[1]]
        tableData6.value = [res.data.cardList[2]]

        let dayInventory = Number(tableData3.value[0].previousBalance) + Number(tableData3.value[0].newCollar) + Number(tableData3.value[0].allotOut) - Number(tableData3.value[0].sendOut) + Number(tableData3.value[0].recycle)
        tableData3.value[0].dayInventory = dayInventory;
        let dayInventory2 = Number(tableData5.value[0].previousBalance) + Number(tableData5.value[0].newCollar) - Number(tableData5.value[0].sendOut)
        tableData5.value[0].dayInventory = dayInventory2;
        let dayInventory3 = Number(tableData6.value[0].previousBalance) + Number(tableData6.value[0].newCollar) - Number(tableData6.value[0].sendOut)
        tableData6.value[0].dayInventory = dayInventory3;


      } else if (activeName.value == 8 && res.data.cardList.length == 0) {
        tableData3.value = [{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: 'CPC卡' }]
        tableData5.value = [{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: '微机票' }]
        tableData6.value = [{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: '节假日纸券' }]
      }

    } else {
      if (activeName.value == 8) {
        tableData3.value = [{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: 'CPC卡' }]
        tableData5.value = [{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: '微机票' }]
        tableData6.value = [{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '', type: '节假日纸券' }]
      } else {
        tableData4.value = [{ previousBalance: '', newCollar: '', allotIn: '', allotOut: '', sendOut: "", recycle: '', dayInventory: "", stationInventory: '' }]
      }

    }

  });
};


const bindChangeRoutine = (val, name, index) => {
  if (activeName.value == 8) {



    // 计算票证方式

    if (index == 0) {
      tableData3.value[index][name] = val;

      let dayInventory = Number(tableData3.value[index].previousBalance) + Number(tableData3.value[index].newCollar) + Number(tableData3.value[index].allotOut) - Number(tableData3.value[index].sendOut) + Number(tableData3.value[index].recycle)
      tableData3.value[index].dayInventory = dayInventory

    } else if (index == 1) {
      tableData5.value[0][name] = val;
      let dayInventory2 = Number(tableData5.value[0].previousBalance) + Number(tableData5.value[0].newCollar) - Number(tableData5.value[0].sendOut)
      tableData5.value[0].dayInventory = dayInventory2

    } else {
      tableData6.value[0][name] = val;
      let dayInventory3 = Number(tableData6.value[0].previousBalance) + Number(tableData6.value[0].newCollar) - Number(tableData6.value[0].sendOut)
      tableData6.value[0].dayInventory = dayInventory3

    }


  }
}

const bindFixed = (val, index, name) => {

  if (!val) { return; }
  if (val == '-' || val == '+') { val = ""; postData.value[index][name] = ''; return; }
  let arr = val.split('.')
  postData.value[index][name] = arr.length == 2 && arr[1].length == 1 ? val + '0' : arr.length == 2 && arr[1].length > 2 ? Number(val).toFixed(2) : arr.length == 1 ? val + '.00' : arr.length == 2 && arr[1].length == 0 ? val + '00' : val

  let total = 0
  postData.value.forEach(item => {
    total = proxy.cal.accAdd(Number(item.fee), total)
  })
  tableData2.value[1].total = total
}
const clearPlusMinus = (val, index, name) => {
  if (val == '-' || val == '+') { val = ""; postData.value[index][name] = ''; return; }
  let total = 0
  postData.value.forEach(item => {
    total = proxy.cal.accAdd(Number(item[name]), total)
  })
  let layIndex = name == 'exTraffic' ? 1 : name == 'enTraffic' ? 2 : 3
  if (selectAccordion.value == 5 || selectAccordion.value == 6 || selectAccordion.value == 7) { layIndex = 1 }
  tableData.value[layIndex].total = total
}
const bindChangeForm = (val, index, name, type) => {
  // val&&val.substr(-1)!="."?Number(val):


  if (type == 1) {
    postData.value[index][name] = val && val.substr(-1) != "-" ? Number(val) : val;
  } else if (type == 2) {
    postData.value[index][name] = val;
    postDataNumber.value[index] = { [name]: val && val.substr(-1) != "." && val.substr(-1) != "-" ? Number(val) : val }
  }




}

const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptName.value = res.user.dept.deptName;
      deptId.value = res.user.dept.deptId;
      queryParams.value.deptId = res.user.dept.deptId;
      queryParams.value.reportDate = selectDate.value
      rowDetails.value = { userName: res.user.nickName, userId: res.user.userId, deptId: res.user.dept.deptId, deptName: res.user.dept.deptName, phonenumber: res.user.phonenumber, postId: res.user.postIds }
      getList()
    }

  })
}
const bindChangeRemark = (val) => {
  remark.value = val;
}
const bindSubmit = () => {
  if (activeName.value == 8) {

    addCardTicke({ cardList: activeName.value == 8 ? [tableData3.value[0], tableData5.value[0], tableData6.value[0]] : tableData4.value, ...queryParams.value, ticketName: ticketName.value }).then(res => {
      if (res.code == 200) {
        statusArr.value.push(ticketName.value)
        proxy.$modal.msgSuccess("提交成功");
        getList()
      }
    });
  } else {
    // postDataNumber
    let list = JSON.parse(JSON.stringify(postData.value))
    postDataNumber.value.forEach((item, index) => {
      list[index] = { ...list[index], ...item }
    })
    addTicke({ list: list, ...queryParams.value, remark: remark.value, ticketName: ticketName.value }).then(res => {
      if (res.code == 200) {
        statusArr.value.push(ticketName.value)
        proxy.$modal.msgSuccess("提交成功");
        getList()
      }
    });
  }

}
// 申请修改
function getformTransferModel(title, id) {
  let postdata = { ...rowDetails.value, message: rowDetails.value.deptName + "的" + rowDetails.value.userName + "在" + moment().format("YYYY-MM-DD") + "发起申请，请求修改" + queryParams.value.reportDate + '提交的' + title, id: info.value.id ? info.value.id : id, reportDate: moment().format("YYYY-MM-DD") }
  let data = { "deployId": "1140058", "procDefId": "flow_ht3yp1mg:2:1140061", "checkedAssignMap": {}, "comment": "", "variables": postdata, "formData": postdata }
  definitionStart(data).then(response => {
    proxy.$modal.msgSuccess("申请成功，等待审核");
    getList();
  });
};
const bindSelectDate = (val) => {
  getList(moment(val).format('YYYY-MM-DD'))
  activeName.value = -1;
  if( postData.value&& postData.value.length){
    postData.value.forEach(item=>{
      item.fee='';
      item.enTraffic='';
      item.exTraffic='';
    })
  }


 
  localhostData.value = [{ title: '收费站现金客车日报表' }, { title: '收费站现金货车日报表' }, { title: '收费站ETC客车日报表' }, { title: '收费站ETC货车日报表' }, { title: '收费站非现金客车日报表' }, { title: '收费站非现金货车日报表' }, { title: '运输鲜活农产品车辆日报表' }, { title: '卡券使用情况报表' }, { title: '特殊情况备注' }]
}

// 历史数据
const bindHistoryShow = () => {
  getSupplementList({ deptId: deptId.value, }).then(res => {
    if (res.code == 200 && res.data) {
      res.data.forEach((opt, i) => {
        historyData.value.forEach((item, index) => {
          if (item.reportType == opt.reportType) {
            historyData.value[index] = { ...opt, ...historyData.value[index] }
          }
        })

      })
    }
    open.value = true;
  })

}
const bindChangeHistory = (val, name, index) => {
  historyData.value[index][name] = val;
  historyData.value[index].deptId = deptId.value;
  saveArr.value.push(historyData.value[index])
}
const cancel = () => {
  open.value = false;
}
const init = () => {
  var strDate = moment().subtract(1, 'days').format("YYYY-MM-DD")
  selectDate.value = strDate;
  queryParams.value.reportDate = strDate;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('statistics/generateInformationCenter', {
    ...queryParams.value, startDate: queryParams.value.reportDate, endDate: queryParams.value.reportDate
  }, `站日报表_${new Date().getTime()}.xlsx`)
}
function handleDay() {
  proxy.download('statistics/generateDayExcelForm', {
    deptId: deptId.value, startDate: queryParams.value.reportDate, endDate: queryParams.value.reportDate
  }, `收费站日报表_${new Date().getTime()}.xlsx`)
}

const submitForm = () => {
  postSupplement(saveArr.value).then(res => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("保存成功");
      open.value = false;
    }
  })
}

/**
 * 判断给定时间是否在当前时间的35小时之内
 * @param {string|Date} time - 要判断的时间
 * @param {number} [hours=35] - 可选参数，指定小时数，默认35
 * @returns {boolean} - 如果在指定时间之内返回true，否则返回false
 */
const isWithinHours = (time, hours = 35) => {
  if (!time) return false

  try {
    const targetTime = moment(time)
    const now = moment()



    // 验证时间是否有效
    if (!targetTime.isValid()) {
      return false
    }

    // 计算时间差（毫秒）
    const diffMs = now.diff(targetTime)
    const hourMs = hours * 60 * 60 * 1000

    return diffMs >= 0 && diffMs < hourMs

  } catch (error) {
    console.error('时间判断错误:', error)
    return false
  }
}
init()
getDeptId()

</script>
  
  
<style scoped >
.container-header {
  display: flex;
  align-items: center;
  padding-bottom: 15px;
  color: #333;
  font-size: 14px;
}
.container-header img {
  width: 18px;
  height: 18px;
}
.container-header .header-title {
  font-size: 16px;
  font-weight: 700;
  padding: 0 12px 0 4px;
  line-height: 23px;
}
.submit {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.text-orange {
  color: #ff920d;
}
.text-green {
  color: #33b388;
}
.text-red {
  color: #7933b3;
}
.accordion-title {
  font-size: 14px;
  color: #333;
  font-weight: 700;
  padding-left: 22px;
}

/* 改element */
.el-collapse {
  border-top: none;
  border-bottom: none;
}
.el-collapse-item {
  border-top: 1px solid #f5f5f5;
  border-left: 1px solid #f5f5f5;
  border-right: 1px solid #f5f5f5;
  margin-bottom: 12px;
}
/deep/ .el-collapse-item__wrap {
  background: #fafafa !important;
  border-radius: 0px 0px 0px 0px;
  border: 1px solid #e4e4e4;
  padding: 17px;
  box-sizing: border-box;
}

/deep/ .el-table .warning-row {
  background: #e0eafb !important;
  text-align: center;
}
/deep/ .el-table .success-row {
  background: #ffeed9 !important;
  text-align: center;
}
/deep/ .el-table .info-row {
  background: #eaeaea !important;
  text-align: center;
}
/deep/ .el-table--default .el-table__cell {
  padding: 0;
}
/deep/ .el-table--default .cell {
  height: 50px;
  line-height: 50px;
  padding: 0;
}
/deep/ .el-collapse-item__content {
  padding-bottom: 0;
}
.inputDeep >>> .el-input.is-disabled .el-input__wrapper {
  background: #fff;
}
.inputDeep {
  width: 100%;
}
.inputDeep >>> .el-input__inner {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: none !important;
  width: 100%;
  box-shadow: none !important;
}

.inputDeep >>> .el-input__inner:focus {
  outline: none;
}
.inputDeep >>> .el-input__wrapper {
  height: 50px;
  line-height: 50px;
  box-shadow: none !important;
}
.inputDeep >>> .el-input__wrapper:hover {
  box-shadow: none !important;
}
.inputDeep >>> .el-textarea__inner {
  height: 80px !important;
  line-height: 40px !important;
  min-height: 50px !important;
  box-shadow: none !important;
  border: none;
}

.inputDeep >>> .el-descriptions__table.is-bordered .el-descriptions__cell {
  width: 100px;
  text-align: center;
}
/deep/ .el-table__body tr > td.el-table__cell.bg-orange {
  background: #ff9e9e;
  padding-left: 10px;
}
</style>